package com.mobilebsc.httpclient.callback;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;

import android.util.Log;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mobilebsc.datatype.EDataType;
import com.mobilebsc.datatype.WeakSignal;
import com.mobilebsc.exception.NotImplementedException;

public class WeakSignalRestClientUsage implements IRestClientUsage<WeakSignal>,
		IAsyncTaskCompleteListener<List<WeakSignal>> {

	private static final String TAG = "WeakSignalRestClientUsage";
	private IAsyncTaskCompleteListener<List<WeakSignal>> callback;
	private String svcUrl;

	public WeakSignalRestClientUsage(
			IAsyncTaskCompleteListener<List<WeakSignal>> callback) {
		this.callback = callback;
		this.svcUrl = "weaksignals";
	}

	@Override
	public void onTaskComplete(List<WeakSignal> result) {
		Log.i(TAG, "result[0].content: " + result.get(0).getId() + ", "
				+ result.get(0).getName() + ", "
				+ result.get(0).getDescription());

		callback.onTaskComplete(result);
	}

	@Override
	public void getAll() {
		WeakSignalHttpResponseHandler httpResponseHandler = new WeakSignalHttpResponseHandler(
				this);
		MbscRestClient.get(svcUrl, null, httpResponseHandler);
	}

	@Override
	public void getById(int weakSignalId) {
		WeakSignalHttpResponseHandler httpResponseHandler = new WeakSignalHttpResponseHandler(
				this);
		MbscRestClient.get(svcUrl, new RequestParams("id", weakSignalId),
				httpResponseHandler);
	}

	@Override
	public void add(WeakSignal element) {
		try {
			StringEntity entity = new StringEntity(element.getJSON().toString());
			MbscRestClient.post(svcUrl + "/write", null, entity,
				new AsyncHttpResponseHandler());
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, "add = " + e.toString());
		} catch (JSONException e) {
			Log.e(TAG, "add = " + e.toString());
		}
	}

	@Override
	public void delete(WeakSignal element) {
		throw new NotImplementedException();

	}

	public void getReferencedWeakSignals(int referenceId,
			EDataType referenceType) {
		WeakSignalReferencedByX_HttpResponseHandler httpResponseHandler = new WeakSignalReferencedByX_HttpResponseHandler(
				this);
		switch (referenceType) {
		case KPI:
			MbscRestClient.get(svcUrl + "/kpi", new RequestParams("id",
					referenceId), httpResponseHandler);
			break;
		default:
			throw new NotImplementedException();
			// break;
		}
	}
}